package com.isoftstone.app.controller.pay;

import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Tidings;
import com.isoftstone.merchant.entity.feeUser.MFeeUser;
import com.isoftstone.merchant.entity.merchant.Merchant;
import com.isoftstone.merchant.entity.mproject.MProject;
import com.isoftstone.merchant.entity.payment.Payment;
import com.isoftstone.merchant.service.feeUser.impl.FeeUserServiceImpl;
import com.isoftstone.merchant.service.merchant.impl.MerchantServiceImpl;
import com.isoftstone.merchant.service.mproject.impl.MProjectServiceImpl;
import com.isoftstone.merchant.service.payment.impl.MPaymentDetialService;
import com.isoftstone.merchant.service.payment.impl.PaymentServiceImpl;
import com.isoftstone.util.BocHttpUtil;
import com.isoftstone.util.Const;
import com.isoftstone.util.DateUtil;
import com.isoftstone.util.Logger;
import com.isoftstone.util.docment.DocumentWrite;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhaojg
 * @Description
 * @Date: Created in 9:10 2017/12/22
 * @Modified by:
 * <p>
 * 支付接口
 */

@Controller
public class PayController extends BaseController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    FeeUserServiceImpl feeUserService;

    @Autowired
    MerchantServiceImpl merchantService;

    @Autowired
    MProjectServiceImpl mProjectService;

    @Autowired
    PaymentServiceImpl paymentService;

    @Autowired
    MPaymentDetialService paymentDetialService;

    /**
     * @param feeUserId 缴费人员id
     * @param projectId 缴费项目id
     * @param corpId    缴费单位id
     * @param payId     缴费流水号
     * @param token     token
     * @return
     */
    @RequestMapping(value = "app/admin/kjBocPay", method = RequestMethod.POST)
    @ResponseBody
    public Tidings<Object> sendPaymentRequest(String feeUserId, Long projectId, String corpId, Long payId, String token, HttpServletRequest request) {

        feeUserId = "1515038831535004";
        projectId = 1515038831535003L;
        corpId = "411";
        payId = 1515038831535006L;

        String acctNo = null;

        Tidings<Object> tidings = new Tidings<Object>();
        try {
            // 找到对应的缴费用户
            MFeeUser feeUser = feeUserService.getFeeUserById(feeUserId);
            if (null == feeUser) {
                tidings.setMsg("没有查到缴费用户");
                tidings.setStatus(Const.MYJFYH);
            } else {
                // 检查用户状态
                String feeUserStatus = feeUser.getStatus();
                if (feeUserStatus != null && StringUtils.equals(feeUserStatus, "1")) {
                    //检查corpId和该缴费用户的缴费单位是否一致
                    String queryCorpId = feeUser.getCorpId();
                    if (queryCorpId == null || !StringUtils.equals(corpId, queryCorpId)) {
                        tidings.setMsg("缴费单位不存在");
                        tidings.setStatus(Const.JFDWBCZ);
                    } else {
                        Merchant merchant = merchantService.getMerchantByCorpId(corpId);
                        //用前台传递的projectId查询缴费项目
                        MProject mProject = mProjectService.getMProjectByProjectId(projectId);
                        String mProjectStatus = mProject.getStatus();
                        Long mProjectProjectId = mProject.getProjectId();
                        //检查缴费单位的状态
                        String merchantStatus = merchant.getStatus();
                        if (merchantStatus != null && StringUtils.equals(merchantStatus, "1") && StringUtils.equals(mProjectStatus, "1") && mProjectProjectId.equals(projectId)) {
                            //查询缴费订单
                            Payment payment = paymentService.getPaymentByPayId(payId);
                            if (payment == null) {
                                tidings.setMsg("缴费订单不存在");
                                tidings.setStatus(Const.JFDDBCZ);
                            } else {
                                if (StringUtils.equals(payment.getPayStatus(), Const.YJF)) {
                                    tidings.setMsg("该缴费订单已支付");
                                    tidings.setStatus(Const.DDYZF);
                                } else {
                                    //根据feeUserId和payId查询缴费订单详细信息
                                    Payment sendPayment = paymentService.queryPaymentByPayIdAndFeeUserId(payId, feeUserId);
                                    if (sendPayment != null) {

                                        //获取卡号
                                        List<Map<String, String>> card = BocHttpUtil.getBocCard(request, "01");
                                        for (Map<String, String> map : card) {
                                            acctNo = map.get("acctNo");
                                        }
                                        //生成xml报文
                                        String sendXml = DocumentWrite.xmlWriteMessage(acctNo, sendPayment);
                                        System.out.println("sendXml = " + sendXml);
                                        logger.info("==============给csp发送的xml缴费报文===========" + sendXml);
                                        //调中银平台接口发送xml报文,并获取返回的数据,进行解析，存到map中
                                        Map<String, String> payMap = BocHttpUtil.sendkjPay(sendXml, request);
                                        if (payMap != null && payMap.size() > 0) {

                                            //首先判断csp交易状态码,如果返回状态码为成功
                                            String err_code = payMap.get("ERR_CODE");
                                            if (StringUtils.equals(err_code, Const.CSPSUCCESS)) {
                                                /**
                                                 * 根据payId更新m_payment_main 、m_payment_detail表记录
                                                 * 这个payId可能是  csp快缴交易流水号FRONT_TRACENO
                                                 */
                                                Payment retPayment = new Payment();
                                                //缴费流水号
                                                retPayment.setPayId(Long.valueOf(payMap.get("FRONT_TRACENO")));
                                                //实际扣款金额
                                                retPayment.setFactAmt(Double.parseDouble(payMap.get("PAY_AMOUNT")));
                                                //支付流水号
                                                retPayment.setPaySeq(payMap.get("CSPS_TRACENO"));
                                                //支付时间(扣款成功日期+扣款成功时间)
                                                retPayment.setPayDate(DateUtil.fomatDate(payMap.get("PAY_DATE") + payMap.get("PAY_TIME")));
                                                //支付类型（线上支付，存支付的银行卡号）
                                                retPayment.setPayType(acctNo);
                                                //支付状态（已缴费）
                                                retPayment.setPayStatus(Const.YJF);
                                                //支付账号（csp返回）
                                                retPayment.setPayAcount(payMap.get("PAY_TRACENO"));
                                                //更新时间
                                                retPayment.setUpdateDate(new Date());
                                                //更新人
                                                retPayment.setUpdator("");

                                                //更新m_payment_main表数据
                                                paymentService.updatePaymentByPayId(retPayment);

                                                //更新m_payment_detail表数据
                                                paymentDetialService.updatePaymentDetail(Long.valueOf(payMap.get("FRONT_TRACENO")), Double.parseDouble(payMap.get("PAY_AMOUNT")));
                                                tidings.setMsg("缴费成功");
                                                tidings.setStatus(Const.SUCCESS);
                                                tidings.setT(retPayment);
                                            }
                                            if (StringUtils.equals(err_code, Const.CSPCHONGFU)) {
                                                tidings.setMsg("重复提交支付");
                                                tidings.setStatus(Const.CSPCHONGFU);
                                            }
                                            if (StringUtils.equals(err_code, Const.CSPERROR)) {
                                                tidings.setMsg("支付失败");
                                                tidings.setStatus(Const.CSPERROR);
                                            }
                                        } else {
                                            tidings.setMsg("csp返回结果异常");
                                            tidings.setStatus(Const.ERROR);
                                        }
                                    }
                                }
                            }
                        } else {
                            tidings.setMsg("缴费项目不存在");
                            tidings.setStatus(Const.JFXMBCZ);
                        }
                    }
                }
            }

        } catch (Exception e) {
            tidings.setMsg("失败");
            tidings.setStatus(Const.ERROR);
            e.printStackTrace();
        }

        return tidings;

    }

}
